import http from "http";
import { Readable } from "stream";
import zlib from "zlib";
import HadaProxy from "./Proxy";

export default class Response {
	body?: Buffer;
	private _source?: http.IncomingMessage;
	statusCode: number = 200;
	headers: http.IncomingHttpHeaders = {};
	statusMessage?: string = "";
	resRaw?: NodeJS.ReadableStream;
	private _hadaProxy: HadaProxy;

	sendToClient(toClient: http.ServerResponse) {
		toClient.writeHead(this.statusCode, this.statusMessage, this.headers);
		// this.resRaw.on("end", () => {
		// 	console.log("响应结束");
		// });

		const readable = this.body ? Readable.from(this.body) : this.resRaw;
		if (readable) {
			readable.pipe(toClient);
		}
	}

	constructor(hadaProxy: HadaProxy) {
		this._hadaProxy = hadaProxy;
	}

	setSource(res: http.IncomingMessage | Response) {
		if (!(res instanceof Response)) {
			this._source = res;
			this.resRaw = res;
		}
		this.statusCode = res.statusCode ?? 200;
		this.headers = res.headers;
		this.statusMessage = res.statusMessage;
	}

	readBody(): Promise<void> {
		if (!this._source) {
			return Promise.resolve();
		}
		return new Promise((resolve, reject) => {
			let readable: NodeJS.ReadableStream = this._source!;
			let body: Buffer[] = [];
			if (this.headers && this.headers["content-encoding"] === "gzip") {
				// TODO: test coverage
				let gunzip = zlib.createGunzip();
				readable = readable.pipe(gunzip);
				delete this.headers["content-encoding"];
			}
			readable.on("error", (err) => {
				reject(err);
			});
			readable.on("data", (chunk: any) => {
				body.push(chunk);
			});
			readable.on("end", () => {
				this.body = Buffer.concat(body);
				resolve();
			});
		});
	}
}
